package com.lepu.app.main.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import lib.share.utils.CallBack;
import lib.share.utils.ShareLib;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.app.application.MyApplication;
import com.app.config.AppConfig;
import com.app.utils.Const;
import com.app.utils.DateUtil;
import com.app.utils.LocationUtil;
import com.app.utils.LoginUtil;
import com.app.utils.MyNetUtil;
import com.app.utils.ObserverConst;
import com.app.utils.SdLocal;
import com.app.utils.Setting;
import com.app.utils.UmengEvent;
import com.app.utils.UpdateManager;
import com.baidu.android.pushservice.PushConstants;
import com.baidu.android.pushservice.PushManager;
import com.core.lib.adapter.FragmentPageAdapter;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.Observer;
import com.core.lib.utils.ObserverManager;
import com.core.lib.utils.main.AppManager;
import com.core.lib.utils.main.LogUtilBase;
import com.core.lib.utils.main.UmengHelper;
import com.core.lib.utils.main.UtilityBase;
import com.core.lib.widget.MenuBarView;
import com.core.lib.widget.MenuBarView.OnMenuBarListener;
import com.core.lib.widget.MyDialog;
import com.core.lib.widget.NoScrollViewPager;
import com.lepu.app.fun.bbs.BbsSearchActivity;
import com.lepu.app.fun.bbs.BbsSendActivity;
import com.lepu.app.fun.chat.util.SingManager;
import com.lepu.app.fun.health.activity.HealthWebActivity;
import com.lepu.app.fun.index.bean.BeanIndexNew;
import com.lepu.app.fun.my.IntegralAnimaSimpleActivity;
import com.lepu.app.fun.my.MyLectureDetailActivity;
import com.lepu.app.fun.my.MyMassegeActivity;
import com.lepu.app.fun.my.MyUserModifyNameActivity;
import com.lepu.app.fun.my.bean.BeanMessage;
import com.lepu.app.fun.my.bean.BeanMsg;
import com.lepu.app.fun.my.bean.BeanMsgBbs;
import com.lepu.app.fun.my.bean.BeanMsgSystem;
import com.lepu.app.main.fragment.MainTabFragmentBbs;
import com.lepu.app.main.fragment.MainTabFragmentHealth;
import com.lepu.app.main.fragment.MainTabFragmentIndex;
import com.lepu.app.main.fragment.MainTabFragmentLecture;
import com.lepu.app.main.fragment.MainTabFragmentMy;
import com.lepu.app.main.permission.PermissionUtil;
import com.lepu.app.main.push.PushUtils;
import com.lepu.app.usercenter.bean.LoginInfo;
import com.lepu.pasm.R;

public class MainTabActivity extends MainActivityBase implements
		OnMenuBarListener, Observer, AsyncRequest {

	private static final String REQUEST_MSG = "request_msg";
	private static final String REQUEST_MSG_SYSTEM = "request_msg_system";

	public static final int MSG_SHOW_LOGIN_TOKEN_DIALOG = 30;

	private static final int TAB_COUNT = 5;
	private static MainTabActivity mInstance = null;

	private NoScrollViewPager mViewPager = null;
	private MenuBarView mMenuBarView = null;

	private MyDialog mCurrentDialog;// 是否token失效的dialog

	private boolean mRequestStartUp = false;

	private BeanMsg mBeanMsg; // 消息bean
	
	private ImageView mainTopMessageImageView ;

	MainTabFragmentIndex mFragmentIndex;
	MainTabFragmentHealth mFragmentHealth;
	MainTabFragmentLecture mFragmentLecture;
	MainTabFragmentBbs mFragmentBbs;
	MainTabFragmentMy mFragmentMy;

	@SuppressLint("ResourceAsColor")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_tab_activity);

		// 初始化配置信息
		LogUtilBase.LogD(null, "MainActivity=====>>onCreate");
		mInstance = this;

		// 异常退出,恢复当前tabIndex
		int tabIndex = 0;
		if (savedInstanceState != null && savedInstanceState.size() > 0) {
			tabIndex = savedInstanceState.getInt("CurrentTabIndex");
		}
		init(tabIndex);
	}

	@Override
	protected void onStart() {

		if (mRequestStartUp) {
			mNeedDefaultBgForground = true;
		} else {
			mNeedDefaultBgForground = false;
		}
		super.onStart();
		if(mNeedDefaultBgForground)
		{
			//从后台切回前台
			bgForgroundRefresh();
		}
		mNeedDefaultBgForground = true;
		mRequestStartUp = true;
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();

		mInstance = null;
		UpdateManager.getInstance().deleteNotification();
		//AppService.stopAppService(this);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {

		// 异常退出，保存当前tabIndex
		outState.putInt("CurrentTabIndex", getMainMenuSelected());
		super.onSaveInstanceState(outState);
	}

	/*
	 * 在栈中被唤醒时，会进入
	 */
	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);

		//
	}

	@Override
	public void onResume() {
		super.onResume();
		if(showBbsPoint()){
			updateTopMessageImage(true);
		}else{
			int msgCount = BeanMsgSystem.getNewMessageCount(LoginUtil.getUserId());
			if(msgCount > 0){
				updateTopMessageImage(true);
				mBeanMsg.osCount = BeanMsgSystem.getNewMessageCount(LoginUtil.getUserId(),1);
				mBeanMsg.fansCount = BeanMsgSystem.getNewMessageCount(LoginUtil.getUserId(),2);
				mBeanMsg.asdCount = BeanMsgSystem.getNewMessageCount(LoginUtil.getUserId(),3);
				mBeanMsg.transCount = BeanMsgSystem.getNewMessageCount(LoginUtil.getUserId(),4);
			}
			else {
				updateTopMessageImage(false);
				
				mBeanMsg.osCount = 0;
				mBeanMsg.fansCount = 0;
				mBeanMsg.asdCount = 0;
				mBeanMsg.transCount = 0;
				mBeanMsg.bbsCount = 0;
			}
		}
		requestAlarm();
	}

	@Override
	public void onPause() {
		super.onPause();
	}

	public static MainTabActivity getInstance() {
		return mInstance;
	}

	private void init(int tabIndex) {

		initBaiduApiKey();
		initGeTuiWithApiKey();

		mainTopMessageImageView = (ImageView) findViewById(R.id.mainTopMessageImageView);
		// content
		mFragmentIndex = new MainTabFragmentIndex();
		mFragmentHealth = new MainTabFragmentHealth();
		// MainTabFragmentChat fragmentChat = new MainTabFragmentChat();
		mFragmentLecture = new MainTabFragmentLecture();
		mFragmentBbs = new MainTabFragmentBbs();
		mFragmentMy = new MainTabFragmentMy();

		ArrayList<Fragment> fragmentList = new ArrayList<Fragment>();
		fragmentList.add(mFragmentIndex);
		fragmentList.add(mFragmentHealth);
		fragmentList.add(mFragmentLecture);
		fragmentList.add(mFragmentBbs);
		fragmentList.add(mFragmentMy);

		mViewPager = (NoScrollViewPager) findViewById(R.id.mainViewPager);
		mViewPager.setAdapter(new FragmentPageAdapter(
				getSupportFragmentManager(), fragmentList, null, null));
		// 是否可以滑动更新tab
		mViewPager.setNoScroll(true);
		// mViewPager.setOnPageChangeListener(new MyViewChangeListener());

		mViewPager.setOffscreenPageLimit(TAB_COUNT - 1);

		// menubar
		mMenuBarView = (MenuBarView) findViewById(R.id.mainMenuBar);
		mMenuBarView.setOnMenuBarListener(this);
		mMenuBarView.setSelectedIndex(tabIndex);
		updateTopbar(tabIndex);

		// chat 铃声资源
		SingManager.getInstance().preparResource();
		// // TODO: 2015/11/30
		// 开启定时刷新消息弹窗
		LoginUtil.loginOpenFire();
		
		//获取医生列表
		//DoctorManager.getInstance().requestDoctorList(DoctorManager.getInstance());

		// 登录状态改变监听
		ObserverManager.getInstance().addObserver(
				ObserverConst.NOTIFY_MY_LOGIN_STATE_CHANGE, this);
		
		// 第一次使用 或升级
		AppConfig.setConfig(this, Const.CONFIG_APP_FIRST_USE, false);
		AppConfig.setConfig(this, Const.CONFIG_APP_UPGRADE_USE, false);

//		boolean appFirstUse = AppConfig.getConfigBoolean(this,
//				Const.CONFIG_APP_FIRST_USE, true);
//		boolean appUpgradeUse = AppConfig.getConfigBoolean(this,
//				Const.CONFIG_APP_UPGRADE_USE, true);
//		if (appFirstUse || appUpgradeUse) {
//			if (LoginUtil.checkIsLogin()) {
//				AppConfig.setConfig(this, Const.CONFIG_APP_FIRST_USE, false);
//				AppConfig.setConfig(this, Const.CONFIG_APP_UPGRADE_USE, false);
//			} else {
//				Intent intentWebGuide = new Intent(this,
//						AppEnterWebGuideActivity.class);
//				startActivityAnim(intentWebGuide, 0, 0);
//			}
//		}
		
		mBeanMsg = new BeanMsg();
		PermissionUtil.getInstance().checkCommonPermissions(this);

		//获取定位
		LocationUtil.getInstance().getLocationBaidu(this);
	}

	// 以apikey的方式绑定
	private void initBaiduApiKey() {
		PushManager.startWork(getApplicationContext(),

				PushConstants.LOGIN_TYPE_API_KEY,
				PushUtils.getMetaValue(mInstance, "api_key"));
	}

	// 以apikey的方式绑定
	private void initGeTuiWithApiKey() {

		// SDK初始化，第三方程序启动时，都要进行SDK初始化工作
		com.igexin.sdk.PushManager.getInstance().initialize(this.getApplicationContext());

	}

	/**
	 * 从后台切换回前台刷新
	 */
	private void bgForgroundRefresh()
	{
		int currentIndex = getMainMenuSelected();
		switch (currentIndex){
			case 0:
				//index
				mFragmentIndex.request();
				mFragmentHealth.mRefreshFlag = true;
				mFragmentLecture.mRefreshFlag = true;
				mFragmentBbs.mRefreshFlag = true;
				break;
			case 1:
				//health
				mFragmentHealth.request();
				mFragmentIndex.mRefreshFlag = true;
				mFragmentLecture.mRefreshFlag = true;
				mFragmentBbs.mRefreshFlag = true;
				break;
			case 2:
				//lecture
				mFragmentLecture.request();
				mFragmentIndex.mRefreshFlag = true;
				mFragmentHealth.mRefreshFlag = true;
				mFragmentBbs.mRefreshFlag = true;
				break;
			case 3:
				//bbs
                mFragmentBbs.refreshBanner();
				mFragmentIndex.mRefreshFlag = true;
				mFragmentHealth.mRefreshFlag = true;
				mFragmentLecture.mRefreshFlag = true;
				
				break;
			case 4:
				mFragmentIndex.mRefreshFlag = true;
				mFragmentHealth.mRefreshFlag = true;
				mFragmentLecture.mRefreshFlag = true;
				mFragmentBbs.mRefreshFlag = true;
				break;
			default:
				break;
		}
	}

	public int getMainMenuSelected() {
		return mViewPager.getCurrentItem();
	}

	/*
	 * 暂时不使用
	 */
	class MyViewChangeListener implements OnPageChangeListener {

		@Override
		public void onPageScrollStateChanged(int arg0) {

		}

		@Override
		public void onPageScrolled(int position, float positionOffset, int arg2) {

		}

		@Override
		public void onPageSelected(int index) {
			mMenuBarView.setSelectedIndex(index);
		}
	}

	@Override
	public void onMenuBarItemSelected(int menuIndex,View view) {
		if (menuIndex == getMainMenuSelected())
			return;

		mViewPager.setCurrentItem(menuIndex, false);
		updateTopbar(menuIndex);

		if(menuIndex == 1){
			UmengHelper.CustomEvent(this, UmengEvent.event_fuwu);
		}
		else if(menuIndex == 2){
			UmengHelper.CustomEvent(this, UmengEvent.event_jiangzuo);
		}
	}

	/*
	 * 通过lib_core的网络请求，反射调入这个方法
	 */
	public void showDialogTokenLogin(String status) {

		LoginUtil.loginOut();

		if(mFragmentMy != null)
		{
			mFragmentMy.updateLoginState();
		}

		AppManager.getAppManager().finishAllActivityNoClass(
				MainTabActivity.class);

		LoginUtil.jumpLogin(MainTabActivity
				.getInstance());

//		if (mCurrentDialog != null && mCurrentDialog.isShowing()) {
//			mCurrentDialog.dismiss();
//		}
//		mCurrentDialog = null;
//
//		if (mCurrentDialog == null) {
//			int msgId = R.string.login_token_error_dialog_message;
//			if (!TextUtils.isEmpty(status) && status.equals("108")) {
//				msgId = R.string.login_token_error_dialog_message2;
//			}
//			mCurrentDialog = new MyDialog(this)
//					.setMessage(msgId)
//					.setNegativeButton(R.string.app_cancel,
//							new View.OnClickListener() {
//
//								@Override
//								public void onClick(View v) {
//
//								}
//							})
//					.setPositiveButton(R.string.app_ok,
//							new View.OnClickListener() {
//
//								@Override
//								public void onClick(View v) {
//									LoginUtil.jumpLogin(MainTabActivity
//											.getInstance());
//
//								}
//							});
//			mCurrentDialog.create(null);
//			mCurrentDialog.setCancelable(false);
//			mCurrentDialog.setCanceledOnTouchOutside(false);
//			mCurrentDialog.showMyDialog();
//		}
	}

	/**
	 * main thread
	 */
	@Override
	public void notify(String name, Object sender, Object data) {

		if (name.equals(ObserverConst.NOTIFY_MY_LOGIN_STATE_CHANGE)) {
			int type = (Integer) data;
			if (type == LoginInfo.TYPE_LOGIN) {
				// 登录成功监听
				LoginUtil.loginOpenFire();
				
				//获取医生列表
				//DoctorManager.getInstance().requestDoctorList(DoctorManager.getInstance());

				if(mFragmentIndex != null)
				{
					mFragmentIndex.request();
				}

				//重新加载陪诊或转诊页面
				HealthWebActivity healthWebActivity = (HealthWebActivity) AppManager.getAppManager().getActivity(HealthWebActivity.class);
				if(healthWebActivity != null)
				{
					healthWebActivity.reloadLogin();
				}

				//重新加载讲座详情页面
				MyLectureDetailActivity myLectureDetailActivity = (MyLectureDetailActivity) AppManager.getAppManager().getActivity(MyLectureDetailActivity.class);
				if(myLectureDetailActivity != null)
				{
					myLectureDetailActivity.requestInfo();
				}

			} else if (type == LoginInfo.TYPE_LOGOUT) {
				// 登出成功监听
				if(mFragmentMy != null)
				{
					mFragmentMy.updateLoginState();
				}

				if(mFragmentIndex != null)
				{
					mFragmentIndex.request();
				}
			}
		}
	}

	public void updateSignInState(boolean canSignIn)
	{
		TextView mainTopSignInTextView = (TextView) findViewById(R.id.mainTopSignInTextView);
		if(canSignIn)
		{
			mainTopSignInTextView.setEnabled(true);
			mainTopSignInTextView.setBackgroundResource(R.drawable.my_sign_in);
		}else{
			mainTopSignInTextView.setEnabled(false);
			mainTopSignInTextView.setBackgroundResource(R.drawable.my_sign_in_ed);
		}
	}

	/**
	 * 更新 topbar
	 * 
	 * @param menuIndex
	 */
	private void updateTopbar(int menuIndex) {
		LinearLayout leftMessageLayout = (LinearLayout) findViewById(R.id.leftMessageLayout);
		TextView topTitleTextView = (TextView) findViewById(R.id.topTitleTextView);

		LinearLayout topSearchBbsLayout = (LinearLayout) findViewById(R.id.topSearchBbsLayout);
		TextView mainTopSendTieZiTextView = (TextView) findViewById(R.id.mainTopSendTieZiTextView);
		TextView mainTopShareTextView = (TextView) findViewById(R.id.mainTopShareTextView);
		TextView mainTopSignInTextView = (TextView) findViewById(R.id.mainTopSignInTextView);

		if (menuIndex == 0) {
			// index
			leftMessageLayout.setVisibility(View.VISIBLE);

			topTitleTextView.setVisibility(View.VISIBLE);

			topSearchBbsLayout.setVisibility(View.GONE);
			mainTopSendTieZiTextView.setVisibility(View.GONE);

			mainTopShareTextView.setVisibility(View.GONE);
			mainTopSignInTextView.setVisibility(View.VISIBLE);

			topTitleTextView.setText(R.string.main_menu_index);

		}else if (menuIndex == 1) {
			// health
			leftMessageLayout.setVisibility(View.VISIBLE);

			topTitleTextView.setVisibility(View.VISIBLE);

			topSearchBbsLayout.setVisibility(View.GONE);
			mainTopSendTieZiTextView.setVisibility(View.GONE);

			mainTopShareTextView.setVisibility(View.GONE);
			mainTopSignInTextView.setVisibility(View.GONE);

			topTitleTextView.setText("健康服务");

		} else if (menuIndex == 2) {
			// lecture
			leftMessageLayout.setVisibility(View.VISIBLE);

			topTitleTextView.setVisibility(View.VISIBLE);

			topSearchBbsLayout.setVisibility(View.GONE);
			mainTopSendTieZiTextView.setVisibility(View.GONE);

			mainTopShareTextView.setVisibility(View.GONE);
			mainTopSignInTextView.setVisibility(View.GONE);

			topTitleTextView.setText(R.string.main_menu_lecture);

		} else if (menuIndex == 3) {
			// bbs
			leftMessageLayout.setVisibility(View.VISIBLE);

			topSearchBbsLayout.setVisibility(View.VISIBLE);
			mainTopSendTieZiTextView.setVisibility(View.VISIBLE);

			mainTopShareTextView.setVisibility(View.GONE);
			mainTopSignInTextView.setVisibility(View.GONE);

		} else if (menuIndex == 4) {
			// my
			leftMessageLayout.setVisibility(View.VISIBLE);

			topTitleTextView.setVisibility(View.VISIBLE);

			topSearchBbsLayout.setVisibility(View.GONE);
			mainTopSendTieZiTextView.setVisibility(View.GONE);

			mainTopShareTextView.setVisibility(View.VISIBLE);
			mainTopSignInTextView.setVisibility(View.GONE);

			topTitleTextView.setText(R.string.main_menu_my);
		}
	}

	/**
	 * 消息红点显示，隐藏
	 * 
	 * @param isShow
	 */
	private void updateTopMessageImage(boolean isShow) {
			if (isShow) {
				mainTopMessageImageView.setVisibility(View.VISIBLE);
			} else {
				mainTopMessageImageView.setVisibility(View.GONE);
			}
	}

	public void viewClick(View v) {
		int rid = v.getId();
		switch (rid) {
		case R.id.mainTopMessageLayout:

			// 我的消息
			Intent intent = new Intent(MainTabActivity.this,
					MyMassegeActivity.class);
			Bundle bundle = new Bundle();
			bundle.putSerializable("beanMsg", mBeanMsg);
			intent.putExtras(bundle);
			startActivity(intent, true);

			UmengHelper.CustomEvent(this, UmengEvent.event_xiaoxi);
			
			break;
		case R.id.mainTopSendTieZiTextView:
			//发帖
			if(!LoginUtil.jumpLogin(MainTabActivity.this)){
				LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();
				//修改昵称
				if(LoginUtil.checkNamePhone(this, loginInfo.NickName, loginInfo.MobilePhone)){
					Intent intentNickName = new Intent(this,MyUserModifyNameActivity.class);
					startActivity(intentNickName, true);
					return;
				}
				
				startActivity(new Intent(this, BbsSendActivity.class), true);
				UmengHelper.CustomEvent(this, UmengEvent.event_luntan_releasenewarticle);
			}
			break;
		case R.id.mainTopShareTextView:

			UmengHelper.CustomEvent(this, UmengEvent.event_wode_share);

			// 我的app分享
			shareApp();
			break;
		case R.id.topSearchBbsLayout:
			// 搜索帖子
			startActivity(new Intent(this, BbsSearchActivity.class), true);
			UmengHelper.CustomEvent(this, UmengEvent.event_luntan_search);
			break;
		case R.id.mainTopSignInTextView:

			UmengHelper.CustomEvent(this,UmengEvent.event_qiandao);

			MyNetUtil.getInstance().requestSignIn(this,this);
			break;
		default:
			break;
		}
	}

	/**
	 * 请求消息
	 */
	private void requestAlarm() {
		
		if (!LoginUtil.checkIsLogin()) {
			requestSystemAlarm();
			return;
		}

		String url = Setting.getMassegeCountUrl();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);

			params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());
		} catch (Exception e) {
		}
		map.put("ht", params);
		ApiClient.http_post_main(url, map, null, this, REQUEST_MSG, true);
	}

	/**
	 * 请求系统消息
	 */
	private void requestSystemAlarm() {

		String url = Setting.getSystemDataUrl();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);
			params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());

			params.put("MessageType", 1);
			if(LoginUtil.checkIsLogin())
			{
				params.put("RegisterStatu", 1);
			}else{
				params.put("RegisterStatu", 0);
			}
			params.put("AppChannel", UtilityBase.getAppMetedata(this, "UMENG_CHANNEL")); //渠道来源
			params.put("AppVersion", AppManager.getAppVersionName(this)); //app版本
			long useTimeMill = DateUtil.getNowTimeInMillis() - AppConfig.getConfigLong(this, Const.CONFIG_APP_USE_TIME,
					DateUtil.getNowTimeInMillis());
			int useDays = ((int) (useTimeMill/DateUtil.DAY_MILLIS)) + 1;
			params.put("DaysInAPP", useDays); //使用天数

		} catch (Exception e) {
		}
		map.put("ht", params);
		ApiClient.http_post_main(url, map, null, this, REQUEST_MSG_SYSTEM, true);
	}

	/**
	 * 分享app
	 */
	private void shareApp() {
		String imgPath = SdLocal.getAppIconPath(this);
		String shareName = getString(R.string.app_name);

		// 调用官方sdk分享，可以各种形式
		ShareLib.Share(this, shareName, Setting.getShareBaseContent(this), imgPath,
				Setting.getAppOfficialUrl(), false, new CallBack() {
					@Override
					public void callBackSuccess(Object obj) {
						super.callBackSuccess(obj);
						LogUtilBase.LogD(null, "回调成功 callBackSuccess");

						MyNetUtil.getInstance()
								.requestShare(mInstance, 4, "-1");
					}

					@Override
					public void callBackFail(Object obj) {
						super.callBackFail(obj);
						LogUtilBase.LogD(null, "回调成功 callBackFail");
					}
				});
	}

	private void addSignIn(int score)
	{
		if(score > 0)
		{
			updateSignInState(false);

			Intent intentAnima = new Intent(this, IntegralAnimaSimpleActivity.class);
			intentAnima.putExtra("integral", String.valueOf(score));
			startActivity(intentAnima);
		}
	}

	@Override
	public void RequestComplete(Object object, Object data) {
		if (object.equals(REQUEST_MSG)) {
			BeanMsg beanMsg = BeanMsg.parseJsonData((String) data);
			mBeanMsg.bbsCount = mBeanMsg.bbsCount + beanMsg.bbsCount;
			mBeanMsg.osCount = mBeanMsg.osCount + beanMsg.osCount;
			mBeanMsg.fansCount = mBeanMsg.fansCount + beanMsg.fansCount;
			mBeanMsg.asdCount = mBeanMsg.asdCount + beanMsg.asdCount;
			mBeanMsg.transCount = mBeanMsg.transCount + beanMsg.transCount;
			if (showPoint(mBeanMsg)) {
				updateTopMessageImage(true);
			} 
//			else{
//				updateTopMessageImage(false);
//			}

			requestSystemAlarm();
		}else if (object.equals(REQUEST_MSG_SYSTEM)) {
			ArrayList<BeanMessage> beanList = BeanMessage.parseListInfo((String) data);
			if(beanList != null){
				for(BeanMessage beanMessage : beanList)
				{
					BeanMsgSystem item = BeanMsgSystem.getBeanMsgSystem(beanMessage);

					item.userId = LoginUtil.getUserId();
					item.isRead = 0;
					item.type = "1";

					if(!BeanMsgSystem.getMsgIsExist(item.userId, 1, item.messageId)){
						//插入数据库
						BeanMsgSystem.insertMyMessage(item);
					}
				}

				int msgCount = BeanMsgSystem.getNewMessageCount(LoginUtil.getUserId(), 1);
				//mBeanMsg.osCount = mBeanMsg.osCount+msgCount;
				mBeanMsg.osCount = msgCount;
				if(showPoint(mBeanMsg)){
					updateTopMessageImage(true);
				}
				else{
					updateTopMessageImage(false);
				}

			}
		}else if (object.equals(MyNetUtil.REQUEST_SIGN_IN)) {
			hideProgressDialog();

			int changeScore = 0;
			//int totalScore = 0;
			try {
				JSONObject jsonObject = new JSONObject((String) data);
				JSONObject obj1 = (JSONObject) jsonObject.get("Result");
				JSONObject dataObject = (JSONObject) obj1.get("DetailInfo");

				changeScore = dataObject.optInt("ChangeCredits");
				//totalScore = dataObject.optInt("AvailableCredits");
			} catch (JSONException e) {
				e.printStackTrace();
			}

			addSignIn(changeScore);
		}
	}
	
	
	@SuppressWarnings("unused")
	@Override
	public void RequestError(Object object, int errorId, String data) {
		if (object.equals(MyNetUtil.REQUEST_SIGN_IN)) {
			hideProgressDialog();

			String result = (String) data;
			int code = 0;
			JSONObject dataObject = null;
			try {
				JSONObject jsonObject = new JSONObject(result);
				JSONObject obj1 = (JSONObject) jsonObject.get("Result");
				code = obj1.optInt("Status");
			} catch (JSONException e) {
				e.printStackTrace();
			}

			if(code == 902){
				//已签到过
				updateSignInState(false);
			}
		}else if (object.equals(REQUEST_MSG)){
			if(showBbsPoint()){
				updateTopMessageImage(true);
			}
//			else{
//				updateTopMessageImage(false);
//			}
		}
	}

	@SuppressLint("HandlerLeak")
	public Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case MSG_SHOW_LOGIN_TOKEN_DIALOG:
				showDialogTokenLogin("");
			default:
				break;
			}
		}
	};

	public boolean showBbsPoint(){
		boolean flag = false;
		ArrayList<BeanMsgBbs> beanList = BeanMsgBbs.getMyMessage(LoginUtil.getUserId());

		int bbsCount = 0;
		if(beanList != null && beanList.size() > 0)
		{
			bbsCount = beanList.size();

			for(int i=0; i<beanList.size(); i++){
				if(BeanIndexNew.isExist(beanList.get(i).MessageID)){
					bbsCount = bbsCount - 1;
				}
			}
		}

		if(bbsCount > 0){
			flag = true;
			mBeanMsg.bbsCount = bbsCount;
		}else{
			flag = false;
		}
		
		return flag;
	}
	
	public boolean showPoint(BeanMsg beanMsg){
		boolean flag = false;
		if (beanMsg.bbsCount != 0 || beanMsg.osCount != 0 || beanMsg.fansCount != 0 || beanMsg.asdCount != 0 || beanMsg.transCount != 0) {
			flag = true;
		}
		
		return flag;
	}
	
}
